package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;


    // 提交订单
    @Transactional
    public void submitOrder(Orders orders) {

        // 获取用户id
        Long currentId = BaseContext.getCurrentId();
        orders.setUserId(currentId);

        // 根据用户id获取用户个人信息
        User user = userService.getById(currentId);

        // 根据用户id去查购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingLqw = new LambdaQueryWrapper<>();
        shoppingLqw.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingLqw);

        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }

        // 根据收货地址id获取收货详细地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("用户收货地址有误,不能下单");
        }

        // 生成订单号
        long orderId = IdWorker.getId();

        // 计算金额使用，具有原子性
        AtomicInteger amout = new AtomicInteger(0);

        // 组装数据，订单明细表
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(item -> {

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amout.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            // multiply 乘的意思

            return orderDetail;
        }).collect(Collectors.toList());

        // 组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amout.get()));
        orders.setNumber(String.valueOf(orderId));
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()
                + addressBook.getCityName() == null ? "" : addressBook.getCityName()
                + addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()
        );

        // 向订单表中添加数据，单条
        this.save(orders);
        // 向订单明细表中添加数据，多条
        orderDetailService.saveBatch(orderDetailList);

        // 清空本用户的购物车
        shoppingCartService.remove(shoppingLqw);
    }
}
